<?php

namespace yan\backendclient\modules\backendmodule\models;

use Yii;

/**
 * This is the model class for table "{{%backend_module_sql}}".
 *
 * @property integer $id
 * @property string $module_id
 * @property string $targetClass
 * @property integer $created_at
 * @property integer $updated_at
 */
class BackendModuleSql extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%backend_module_sql}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['module_id', 'targetClass'], 'required'],
            [['created_at', 'updated_at'], 'integer'],
            [['module_id'], 'string', 'max' => 48],
            [['targetClass'], 'string', 'max' => 100],
        ];
    }

    public function behaviors()
    {

        $data = \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            'timestamp' => [
                'class' => 'yii\behaviors\TimestampBehavior',
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ]
        ]);
        return $data;
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('debug', 'ID'),
            'module_id' => Yii::t('debug', 'Module ID'),
            'targetClass' => Yii::t('debug', 'Target Class'),
            'created_at' => Yii::t('debug', 'Created At'),
            'updated_at' => Yii::t('debug', 'Updated At'),
        ];
    }
    public function getRawTableName(){
        $targetClass = $this->targetClass;
        if(class_exists($targetClass)){
            return preg_replace_callback(
                '/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
                function ($matches) {
                    if (isset($matches[3])) {
                        return $matches[3];
                    }
                    return str_replace('%', Yii::$app->db->tablePrefix, $matches[2]);
                },
                $targetClass::tableName()
            );
        }
        return false;
    }
}
